package com.thread.xxstudy;

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者-消费者  利用无界阻塞式队列进行增加 删除  主要解决数据的准确
 */
public class ConsumerAndProducter {

    //阻塞式无界队列
    BlockingQueue bq = new LinkedBlockingQueue<String>();

   volatile int a = 0;

    public final static int threadCount = 4;

    ReentrantLock lock = new ReentrantLock();

   /* public static void main(String[] args) {
        ConsumerAndProducter consumerAndProducter = new ConsumerAndProducter();

        Consumer consumer = consumerAndProducter.new Consumer();
        Producter producter = consumerAndProducter.new Producter();

        //初始值为0   随着任务的增加增加线程池
        ExecutorService executorServiceS = Executors.newCachedThreadPool();
        for (int i = 0; i < 20; i++) {
            executorServiceS.submit(consumer);
        }

        ExecutorService executorServiceP = Executors.newFixedThreadPool(threadCount);
        for (int i = 0; i < 3; i++) {
            executorServiceP.submit(producter);
        }

    }*/

    class Consumer implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    //   Thread.sleep(1000);
                   Object take = bq.take();
                    System.out.println(Thread.currentThread().getName() + "拿---" + take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    class Producter implements Runnable {

        @Override
        public void run() {

            while (true) {

                try {
                  /*  //synchronized
                    //不加锁会导致重复塞入多条
                    //1.加入第一条线程拿到a=1 然后休眠1s  这时候第二个线程来的时候发现还有加  所以他拿到a还是1  然后就会重复++a插入多条
                    //2.如果把判断break放在外面  判断也会出问题  导致a>=10的判断 虽然不会重复插入  但是会插入超越10的数字
                    synchronized (this) {
                        if (a >= 10) {
                            break;
                        }
                        //加上这条是为了确保线程在外面等候
                        Thread.sleep(1000);
                        String put = "pc-" + (++a);
                        System.out.println(Thread.currentThread().getName() + "---放" + put);
                        bq.put(put);
                    }*/

                    lock.lock();
                    if (a >= 10) {
                        break;
                    }
                    String put = "pc" + (++a);
                    System.out.println(Thread.currentThread().getName() + "放---" + put);
                    bq.put(put);
                    lock.unlock();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
